const router = require('koa-router')()
const uploader = require('../uploader')
const mongoose = require('mongoose')
const path = require('path')
const fs = require('fs')
const util = require('util')
const stats = require('../helpers/stats')
const comments = require('../helpers/comments')

const rename = util.promisify(fs.rename)

router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')



router.post('/', uploader.single('file'), async function (ctx, next) {
    let file = ctx.req.file
    let diskFilename = file.filename + path.extname(file.originalname)
    await rename(file.path, path.dirname(file.path) + '/' + diskFilename)
        .then(() => Image.create({
            title: ctx.req.body.title,
            description: ctx.req.body.description,
            filename: diskFilename,
            mimetype: ctx.req.file.mimetype,
            originalname: ctx.req.file.originalname
        }))
        .then(doc => {ctx.body = {ok: 1}})
        .catch(err => ctx.throw(500, err))
})

router.get('/:imageid', async function (ctx, next) {
  await Promise.all([
    await Image.findByIdAndUpdate(ctx.params.imageid, {$inc: {views: 1}}),
    Image.findById(ctx.params.imageid),
    Image.find().sort({likes: -1}).limit(6),
    stats(),
    Comment.find({image: ctx.params.imageid}),
    comments()
  ])
    .then(([temp, image, popular, stats, commentis, comments]) => ctx.render('image',
      {image, popular, stats, commentis, comments}
    ))
    .catch(err => ctx.throw(500, err))
})

router.post('/:imageid/comment', async ctx => {
    await Comment.create(Object.assign({}, ctx.request.body, {image: ctx.params.imageid}))
    .then(doc => ctx.body = doc)
    .catch(err => ctx.throw(500, err))
})

router.post('/:id/like', async ctx => {
  await Image.findByIdAndUpdate(ctx.params.id, {$inc: {likes: 1}})
  .then(() => Image.findById(ctx.params.id))
  .then(doc => ctx.body = {likes: doc.likes})
  .catch(err => ctx.throw(500, err))
})

router.del('/:id', async ctx => {
  await Image.findByIdAndRemove(ctx.params.id)
  await Comment.remove({image: ctx.params.id})
  .then(() => ctx.body = {ok: 1})
  .catch(err => ctx.throw(500, err))
})

module.exports = router
